package com.hxut.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hxut.common.dto.PassDto;
import com.hxut.common.lang.Const;
import com.hxut.common.lang.Result;
import com.hxut.entity.SysRole;
import com.hxut.entity.SysUser;
import com.hxut.entity.SysUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MR.S
 * @since 2022-06-21
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * @description:  编辑用户信息
     * @param id
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 21:03
    */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result info(@PathVariable Long id){

        SysUser sysUser = sysUserService.getById(id);
        Assert.notNull(sysUser,"找不到该用户");

        List<SysRole> sysRoles=sysRoleService.listRoleByUserId(id);

        sysUser.setSysRoles(sysRoles);
        return Result.success(sysUser);
    }

    /**
     * @description:  分页查询
     * @param username
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 21:05
    */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(String username){
        Page<SysUser> page = sysUserService.page(getPage(), new QueryWrapper<SysUser>().
                like(StrUtil.isNotBlank(username), "username", username));

        page.getRecords().stream().forEach(user -> {
            user.setSysRoles(sysRoleService.listRoleByUserId(user.getId()));
        });
        return Result.success(page);
    }

    /**
     * @description:  新增用户
     * @param sysUser
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 21:36
    */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUser sysUser){
        sysUser.setCreated(LocalDateTime.now());
        sysUser.setStatu(Const.STATE_ON);

        //默认密码 88888
        String password = passwordEncoder.encode(Const.DEFAULT_PASSWORD);
        sysUser.setPassword(password);

        //默认头像
        sysUser.setAvatar(Const.DEFAULT_AVATAR);
        sysUserService.save(sysUser);
        return Result.success(sysUser);
    }

    /**
     * @description:  更新用户信息
     * @param sysUser
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 22:05
    */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result update(@Validated @RequestBody SysUser sysUser){

        sysUser.setUpdated(LocalDateTime.now());

        sysUserService.updateById(sysUser);
        return Result.success(sysUser);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] ids){
        sysUserService.removeByIds(Arrays.asList(ids));
        //删除关联表数据
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id",ids));

        return Result.success("删除成功");
    }

    /**
     * @description:  授予权限
     * @param userId
     * @param roleIds
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 23:20
    */
    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable("userId") Long userId,@RequestBody Long[] roleIds){
      //根据页面传递的用户id,角色id数组，构造关联表sys_user_role的数据
      List<SysUserRole> userRoles = new ArrayList<>();

      Arrays.stream(roleIds).forEach(roleId->{
          SysUserRole sysUserRole = new SysUserRole();

          sysUserRole.setUserId(userId);
          sysUserRole.setRoleId(roleId);

          userRoles.add(sysUserRole);
      });

      //先删除权限信息，再插入
      sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",userId));
      sysUserRoleService.saveBatch(userRoles);

      //权限发生变化时，删除缓存
      SysUser sysUser = sysUserService.getById(userId);
      sysUserService.clearUserAuthorityInfo(sysUser.getUsername());
      return Result.success("授予权限成功");
    }

    /**
     * @description:  重置密码默认88888
     * @param userId
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 23:35
    */
    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result resetPasswd(@RequestBody Long userId){

        //根据userid查询相关用户信息
        SysUser sysUser = sysUserService.getById(userId);

        //重置密码(更新操作)
        sysUser.setPassword(passwordEncoder.encode(Const.DEFAULT_PASSWORD));
        sysUser.setUpdated(LocalDateTime.now());

        sysUserService.updateById(sysUser);

        return Result.success("重置密码成功");
    }

    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal){
        SysUser sysUser = sysUserService.getByUsername(principal.getName());

        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if(!matches){
            return Result.fail("旧密码不正确");
        }

        sysUser.setPassword(passwordEncoder.encode(passDto.getPassword()));
        sysUser.setUpdated(LocalDateTime.now());

        sysUserService.updateById(sysUser);

        return Result.success("重置密码成功");
    }

}
